<template>
	<ComSearch isInput @handleInput="filterText = $event" :isBtn="false" ref="searchRef"/>
	<div class="tree-list">
		<a-tree
			ref="treeRef"
			:data="treeData"
			:checkable="checkable"
			:check-strictly="treeCheckStrictly"
			:fieldNames="treeProps"
			:expand-on-click-node="false"
			:props="treeDefaultProps"
			@check="handleCheckChange"
			@select="handleSelectChange"
			:default-expand-all="true"
			default-expand-checked
			:multiple="props.multiple"
			highlight-current
			:show-checkbox="treeCheckbox"
			:check-on-click-node="true"
			:filter-node-method="filterNode"
        	v-bind="getBindValue"
		/>
	</div>
</template>
<script setup lang="ts">
import IconAvatar from '@/assets/avatar.png';
const props = defineProps({
  list: { type: Array, default: () => { return [] }},
  params: { type: String, default: () => { return 'name' }},
  treeKey: { type: String, default: () => { return 'id' }},
  treeType: { type: String, default: () => { return '' }},
  treeDefaultProps: { type: Object, default: () => { return {
    children: 'children',
    title: 'name',
    value: 'id',
    key:'id',
    isLeaf: 'leaf',
    emitPath: false // 用于 cascader 组件：在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
  } }},
  treeCheckbox: { type: Boolean, default: () => { return true }}, // 是否展示勾选框
  treeCheckStrictly: { type: Boolean, default: () => { return true }}, // 勾选是否父子分离
  treeExpandAll: { type: Boolean, default: () => { return true }}, // 是否展开所有节点
  treeCheckedList: { type: Array, default: () => { return [] }}, // 回显已勾选
  multiple: { type: Boolean, default: () => { return true } }, // 是否多选
  checkable: { type: Boolean, default: () => { return true } }, //是否在节点前添加复选框
  height:{type:String ,default:()=>{'100%'}},
  filterList: { type: Array, default: () => { return [] }}, // 需要过滤的数据
})
const treeProps = ref(props.treeDefaultProps);
const treeList = ref();
const treeListInt = ref();
const emit = defineEmits(['SendCheckedList', 'SendCurrentNode']);
const treeRef = ref();
const filterText = ref('');
const searchRef = ref(null);

watch(() => props.params, e => {
	treeProps.value.title = e;
}, { immediate: true })

const getBindValue=computed(()=>{
  return {
    selectedKeys: props.treeCheckedList,
    checkedKeys: props.treeCheckedList,
  }
})
const handleSearch = (val) => {
   treeProps.value.key = 'onlyId';
  treeList.value = searchData(val, treeListInt.value);
  if (!val) {
      treeProps.value.key = 'id';
    }
}
// 处理树,添加唯一值
const getTree = (index ,list) => {
  list.forEach(item => {
    item.onlyId=index+'_'+item.id
    if (item.children) {
      getTree(item.id,item.children)
    }
  })
  return list
}

const computedList = computed(() => {
	if(props.treeType === 'dept'){
		nextTick(() => {
			treeRef.value.expandAll(true);
			treeRef.value.checkNode(props.treeCheckedList,true);
		})
		return props.list;
	}else{
		return props.list.filter(item => !props.filterList.some(obj => obj === item.id))
	}
})

// 勾选
const handleCheckChange = async(val, checkRecord) => {
   treeRef.value.selectNode([checkRecord.node?.id],checkRecord.checked)
    // 单选
  if (!props.multiple && val.length == 2) {
     emit('SendCheckedList',[checkRecord.checkedNodes[1]]);
  }else {
    emit('SendCheckedList', checkRecord.checkedNodes)
  }
  
};
const handleSelectChange = (val, checkRecord) => {
  treeProps.value.key = 'id';
  if (!props.multiple && !props.checkable) {
    // 单选
    emit('SendCheckedList', treeRef.value.getSelectedNodes())
  } else {
    // 多选
    treeRef.value.checkNode(checkRecord.node?.id, checkRecord.selected)
    const data = treeRef.value.getCheckedNodes()
    emit('SendCheckedList', data)
  }
}
const filterNode = (value,data) => {
  if (!value) return data
  return data[props.params].includes(value)
}

const treeData = computed(() => {
	if (!filterText.value){
		return computedList.value;
	}
	return searchData(filterText.value);
})

 function searchData(keyword) {
	const loop = (data) => {
		const result = [];
		data.forEach(item => {
			if (item[props.params].toLowerCase().indexOf(keyword.toLowerCase()) > -1) {
				result.push({...item});
			} else if (item.children) {
				const filterData = loop(item.children);
				if (filterData.length) {
					result.push({
						...item,
						children: filterData
					})
				}
			}
		})
		return result;
	}
	return loop(computedList.value);
}


defineExpose({
  filterText,
  treeList,
  searchRef
})

</script>
<style lang="scss" scoped>
.tree-list{
	height: 500px;
	overflow: auto;
	margin-top: 10px;
	:deep(.arco-tree){
		.arco-tree-node-title{
			width: 100%;
		}
		.arco-tree-node{
			&:hover {
				background: #f2f3f5;
			}
		}
	}
	.search-ipt{
		margin-bottom: 10px;
	}
    .tree-item{
        display: flex;
        align-items: center;
        .avatar{
            width: 16px;
            height: 16px;
            border-radius: 50%;
            margin-right: 6px;
        }
    }
}
</style>
